from lib.net import wifi
from utils import common, device
from . import handler


def get_ssd1306_fonts(content):
    """
    获取文本对应1306点阵
    """
    payload = {"content": content}
    resp = wifi.POST(payload, "www.hanxiaoxin.cn", "/poem", 8080)
    return resp


def get_poem_action():
    """
    获取POEM操作
    """
    payload = {
        "type": "query",
        "name": "poem",
        "data": {
            "device_id": device.get_device_id(),
            "device_info": device.get_device_info(),
        },
    }
    print("send fetch poem request")
    resp = wifi.UREQUEST_POST("http://www.hanxiaoxin.cn:8080/action", payload)
    # print(resp)
    handler.handle_poem(resp)
    return resp


def get_ws2812_action():
    """
    获取WS2812操作
    """
    payload = {
        "type": "query",
        "name": "ws2812",
        "data": {
            "device_id": device.get_device_id(),
            "device_info": device.get_device_info(),
        },
    }
    print("send fetch ws28112 request")
    resp = wifi.UREQUEST_POST("http://www.hanxiaoxin.cn:8080/action", payload)
    # print(resp)
    return resp


def get_tts_action(play=False):
    """
    获取tts操作
    """
    payload = {
        "type": "query",
        "name": "tts",
        "data": {
            "device_id": device.get_device_id(),
            "device_info": device.get_device_info(),
        },
    }
    print("send fetch tts request")
    resp = wifi.UREQUEST_POST("http://www.hanxiaoxin.cn:8080/action", payload)
    return handler.handle_tts(resp, play)


def get_tts_audio(content):
    """获取文本的tts json"""
    resp = wifi.UREQUEST_POST(
        "http://www.hanxiaoxin.cn:8080/tts",
        {
            "Text": content,
            "Codec": "wav",
            "EmotionCategory": "poetry",
            "VoiceType": 301000,
        },
    )
    audio_base64 = resp["Audio"]
    audio_data = common.decode_base64(audio_base64)
    with open("/audio.wav", "w") as f:
        f.write(audio_data)
    print("save audio wav")
    return audio_base64


def get_tts_audio_raw(content):
    """直接获取文本的tts音频数据"""
    params = {
        "Text": content,
        "Codec": "wav",
        "EmotionCategory": "poetry",
        "VoiceType": 301000,
        "mime": "wav",
    }
    resp = wifi.UREQUEST_POST("http://www.hanxiaoxin.cn:8080/tts", params, "raw")
    return resp
